package com.example.gateway.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

@Component
public class ResponseWrapperFilter implements GlobalFilter, Ordered {

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取原始响应
        ServerHttpResponse response = exchange.getResponse();

        // 包装响应
        return chain.filter(exchange).then(Mono.fromRunnable(() -> {
            if (response.getStatusCode() == HttpStatus.OK) {
                try {
                    // 获取原始响应体
                    DataBuffer buffer = response.bufferFactory().wrap(
                            objectMapper.writeValueAsBytes(
                                    ApiResponse.success("Response wrapped by gateway")
                            )
                    );
                    // 设置响应头和内容
                    response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
                    response.writeWith(Mono.just(buffer));
                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                }
            }
        }));
    }

    @Override
    public int getOrder() {
        return -1; // 设置过滤器优先级
    }
}